package com.coocaa.ops.common.tool.http;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author bijiahao
 * @date : 2019/6/14.
 * @description
 */
public class HttpSessionUtil {
    public static final String LOCALHOST = "localhost";

    public static HttpSession getSession(HttpServletRequest request) {
        return request.getSession();
    }

    public static Object getSessionValue(HttpServletRequest request, String key) {
        HttpSession session = getSession(request);
        return session.getAttribute(key);
    }

    public static void setSessionValue(HttpServletRequest request, String key, Object val) {
        HttpSession session = getSession(request);
        session.setAttribute(key, val);
    }

    public static void removeSessionValue(HttpServletRequest request, String key) {
        HttpSession session = getSession(request);
        session.removeAttribute(key);
    }

    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        if (ip != null && ip.length() > 0 && ip.indexOf(",") > -1) {
            ip = ip.substring(0, ip.indexOf(","));
        }

        return ip;
    }

    /**
     * 获取服务器本地名称
     *
     * @param request
     * @return
     */
    public static String getLocalName(HttpServletRequest request) {
        String host = request.getLocalName();
        return host;
    }

    /**
     * 是否本地运行
     *
     * @param request
     * @return
     */
    public static boolean isLocal(HttpServletRequest request) {
        String host = getLocalName(request);
        return LOCALHOST.equals(host);
    }

}
